package com.hb.trade.server.center.au.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.center.au.dto.RoleDTO;
import com.hb.core.pojo.center.au.dto.UserDTO;
import com.hb.core.pojo.center.au.dto.UserExtDTO;
import com.hb.core.pojo.center.au.entity.*;
import com.hb.core.pojo.enums.RoleSignEnum;
import com.hb.core.pojo.enums.RoleTypeEnum;
import com.hb.core.pojo.parent.MPCommonEntity;
import com.hb.trade.server.center.au.service.*;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.enums.UserTypeEnum;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.ResultUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 用户模型领域对象
 *
 * @author zhaojk
 */
public class UserManager extends UserDTO {
    /**
     * 判断当前用户是否是超级管理员
     *
     * @return
     */
    public boolean isAdmin() {
        if (getId() == null) {
            return false;
        }
        UserService userService = SpringUtil.getBean(UserService.class);
        User user = userService.getById(getId());

        UserTypeEnum userTypeEnum = Enums.of(UserTypeEnum.class, user.getUserType());
        return userTypeEnum == UserTypeEnum.SUPER_ADMIN;
    }

    /**
     * 更新用户信息时做的验证
     */
    public String verifyUpdate() {
        // 必须携带id参数
        Long id = getId();
        if (id == null) {
            return MsgEnum.INCORRECT_PARAM.msg();
        }

        // 用户名和密码不能更新
        // setPassword(null);
        setUsername(null);
        setSaltSource(null);

        if (isAdmin()) {
            if (id.equals(getUpdateId())) {
                return null;
            }
            return MsgEnum.ADMIN_ERROR.msg();
        }

        // 验证部门参数(如果用户要设置的部门与原来不一致, 并且该用户还是该部门的负责人给出提示)
        UserService userService = SpringUtil.getBean(UserService.class);
        User user = userService.getById(id);
        // 将要设置的部门ID
        Long deptId = getDeptId();
        if (deptId != null) {
            // 用户原来的部门ID
            Long userDeptId = user.getDeptId();
            if (userDeptId == null) {
                return null;
            }
            // 部门设置没有改变直接返回
            if (deptId.equals(userDeptId)) {
                return null;
            }
            OrgDeptService orgDeptService = SpringUtil.getBean(OrgDeptService.class);
            OrgDept orgDept = orgDeptService.getById(userDeptId);
            Long manageId = orgDept.getManageId();
            if (id.equals(manageId)) {
                return "该用户为当前所在部门的负责人, 不能修改";
            }
        }

        return null;
    }

    /**
     * 新增用户时做的验证
     * 该方法会生成默认密码: 123456
     */
    public String verifyAdd() {
        Set<Long> roleIds = getRoleIds();
        if (CollUtil.isEmpty(roleIds)) {
            Integer roleSign = getRoleSign();
            if (roleSign == null) {
                return "新增用户至少设置一个用户角色";
            }
            RoleService roleService = SpringUtil.getBean(RoleService.class);
            Role role;
            role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, roleSign));
            roleIds = CollUtil.set(false, role.getId());
            setRoleIds(roleIds);
        }

        // 逻辑层面的验证
        Integer userType = getUserType();
        if (userType == null) {
            return "必须设置用户类型";
        }
        if (Enums.equals(UserTypeEnum.SUPER_ADMIN, userType)) {
            return "不能新增超级管理员";
        }

        // 数据层面验证
        OrgService orgService = SpringUtil.getBean(OrgService.class);
        Org org = orgService.getById(getOrgId());
        if (org == null) {
            return "对应的企业信息不存在";
        }
        User exists = null;
        UserService userService = SpringUtil.getBean(UserService.class);
//        if (this.getRoleId() != null) {
//            exists = userService.getUserByPhoneAndRoleSign(this.getRoleId(), this.getPhone());
//        }
//        else {
//            exists = userService.exists(this);
//        }
        List<Long> ids = new ArrayList<>();
        // 如果根据roleSign查询该手机号下的全部角色
        if (getRoleSign() != null) {
            RoleService roleService = SpringUtil.getBean(RoleService.class);
            List<Long> roles = roleService.listRoleIdByPhone(getPhone(),getRoleSign());
            ids.addAll(roles);
        }

        ids.addAll(roleIds);
        List<User> users = userService.getUserByPhoneAndRoleSign(ids, this.getPhone(), org.getId());
        if (users != null) {
            if (users.size() > 0) {
                for (User user: users){
                    // 判断是否在同一企业下
                    if (user.getOrgId().equals(org.getId())){
                        exists = users.get(0);
                        continue;
                    }
                    if (org.getOrgName()!=null && org.getParentId().equals(user.getOrgId())){
                        exists = users.get(0);
                    }
                }

            }
        }
        if (exists == null) {
            exists = userService.exists(this);
        }
        if (exists != null) {
            return "用户名或手机号已存在";
        }

        //如果没有密码则设置密码
        if (StrUtil.isEmpty(this.getPassword())) {
            setPassword(INIT_PASSWORD_SECRET);
            setSaltSource(INIT_SALT_VALUE);
        }

        // 新增用户为二级账号
        setAccountLevel(2);

        String paramsValid = paramsValid();
        if (StrUtil.isNotEmpty(paramsValid)) {
            return paramsValid;
        }
        return null;
    }

    /**
     * 删除用户验证
     */
    public String verifyDelete() {
        // 必须携带id参数
        Long id = getId();
        if (id == null) {
            return MsgEnum.INCORRECT_PARAM.msg();
        }

        // 查询数据库中的用户数据
        UserService userService = SpringUtil.getBean(UserService.class);
        User user = userService.getById(id);

        // 判断用户类型, 超级管理员和企业管理员不能删除
        UserTypeEnum userTypeEnum = Enums.of(UserTypeEnum.class, user.getUserType());
        if (userTypeEnum == UserTypeEnum.SUPER_ADMIN) {
            return MsgEnum.ADMIN_NOT_ALLOW_DELETE.msg();
        }
        if (userTypeEnum == UserTypeEnum.ORG_ADMIN) {
            return "企业管理员不能删除";
        }
        return null;
    }
}
